package cn.itsource.smartsystem.interceptor;

import cn.itsource.smartsystem.util.TokenMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入到了拦截器中");
        //从本地储存对象中获取到token之
        String token = request.getHeader("access-token");
        String parameter = request.getParameter("access-token");
        String type = request.getParameter("type");
        if(StringUtils.isNotBlank(parameter)
                && StringUtils.isNotBlank(type)
                && TokenMap.getTokenMap(parameter)!= null){
                  return true ;
        }
        Object o = TokenMap.getTokenMap(token);
       // System.out.println(o);
        if ("".equals(o) || null == o){
            // 1.告诉前端我响应的是一个JSON
            response.setContentType("application/json;charset=UTF-8");
            // 2.设置响应数据
            PrintWriter writer = response.getWriter();
            writer.write("{\"code\":\"401\"}");

            return false; // 拦截
        }
        //登录成功了 直接放行
        return true;
    }
}
